﻿namespace FormsUtilities
{
    using System;
    using System.Windows.Forms;

    public partial class LabeledTextBox : UserControl
    {
        public LabeledTextBox()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Gets or sets the label to the text-box. If not 'null', this is the label to display instead of the usual <see cref="Text"/> property.
        /// </summary>
        public string Label { get; set; }

        /// <summary>
        /// Gets or sets the text to display when this control is in focus.
        /// </summary>
        public string InternalText { get; set; }

        #region UserConrtol overrides

        /// <summary>
        /// The Forms text property
        /// </summary>
        public override string Text
        {
            get
            {
                return innerTextBox.Text;
            }

            set
            {
                innerTextBox.Text = value;
            }
        }

        #endregion

        private void LabeledTextBox_Load(object sender, EventArgs e)
        {
            Height = innerTextBox.Height;

            innerTextBox.Text = string.IsNullOrEmpty(Label) ? InternalText : Label;
        }

        private void innerTextBox_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Label))
            {
                innerTextBox.Text = InternalText;
            }

            innerTextBox.SelectAll();
        }

        private void innerTextBox_Validated(object sender, EventArgs e)
        {
            InternalText = innerTextBox.Text;

            OnValidated(e);

            if (!string.IsNullOrEmpty(Label))
            {
                innerTextBox.Text = Label;
            }
        }

        public override void Refresh()
        {
            if (Focused && !string.IsNullOrEmpty(Label))
            {
                Text = Label;
            }
            else
            {
                Text = InternalText;
            }

            base.Refresh();
        }

        /// <summary>
        /// Forces the label to show on the text-box.
        /// </summary>
        public void ShowLabel()
        {
            Text = Label;

            base.Refresh();
        }
    }
}
